<template>
  <div class="image-uploader">
    <!-- 显示已选择的图片 -->
    <div class="selected-images">
      <div v-if="selectedImages.length > 0" class="image">
        <img :src="selectedImages[0].url" alt="">
        <span class="delete" @click="removeImage(0)">x</span>
      </div>
    </div>

    <!-- 文件选择器 -->
    <input type="file" ref="fileInput" :accept="accept" @change="onFileChange">

    <!-- 上传按钮 -->
    <button class="upload-button" @click="uploadImages" :disabled="selectedImages.length !== 1">
      上传
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedImages: [], // 已选择的图片
      accept: 'image/jpeg,image/png', // 可接受的文件类型
      maxSize: 2 * 1024 * 1024, // 文件最大大小（2MB）
    };
  },
  methods: {
    // 选择文件后触发
    onFileChange(e) {
      const files = e.target.files;
      if (!files) return;

      // 遍历选择的文件
      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 检查文件类型
        if (!this.checkFileType(file)) {
          alert('请上传JPG、PNG、JPEG格式的图片');
          return;
        }

        // 检查文件大小
        if (!this.checkFileSize(file)) {
          alert('请上传小于2MB的图片');
          return;
        }

        // 读取文件内容
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const url = e.target.result;
          this.selectedImages.splice(0, 1, { url, file });
        };
      }

      // 清空文件选择器的值，以便下次选择同一文件时触发change事件
      e.target.value = '';
    },

    // 检查文件类型
    checkFileType(file) {
      return this.accept.split(',').includes(file.type);
    },

    // 检查文件大小
    checkFileSize(file) {
      return file.size <= this.maxSize;
    },

    // 删除已选择的图片
    removeImage(index) {
      this.selectedImages.splice(index, 1);
    },

    // 上传已选择的图片
    uploadImages() {
      // TODO: 实现上传功能
      console.log(this.selectedImages[0]);
    },
  },
};
</script>

<style>
.image-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.selected-images {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-bottom: 10px;
}

.image {
  position: relative;
  margin: 5px;
}

.image img {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.image .delete {
  position: absolute;
  top: -5px;
  right: -5px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  background-color: #f44336;
  color: white;
  font-size: 12px;
  font-weight: bold;
  border-radius: 50%;
  cursor: pointer;
}

.upload-button {
  padding: 10px 20px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  outline: none;
}

.upload-button:disabled {
  background-color: #e0e0e0;
  color: #9e9e9e;
  cursor: not-allowed;
}
</style>
